package spring.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import spring.web.dao.BoardDao;
import spring.web.dto.BoardDto;

@Controller
public class BoardWriteController  {
	
	private BoardDao boardDao;
	
	public void setBoardDao(BoardDao boardDao) {
		this.boardDao = boardDao;
	}
	
	@RequestMapping(value="/board/boardWrite.do" , method=RequestMethod.GET)
	protected ModelAndView boardView(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		ModelAndView mav = new ModelAndView();
		
		if (request.getParameter("seq") != null) {
			int seq = Integer.parseInt(request.getParameter("seq"));
			BoardDto boardDto = boardDao.getView(seq);
			
			mav.addObject("boardDto" , boardDto);
		}
		
		mav.setViewName("boardWrite");
		return mav;
	}
	
	@RequestMapping(value="/board/boardWrite.do" , method=RequestMethod.POST)
	protected ModelAndView boardUpdate(HttpServletRequest request,
			HttpServletResponse response	)
			throws Exception {
		
		ModelAndView mav = new ModelAndView();
		String WRITER = request.getParameter("WRITER");
		String PASSWORD = request.getParameter("PASSWORD");
		String TITLE = request.getParameter("TITLE");
		String CONTENT = request.getParameter("CONTENT");
		String SEQ = request.getParameter("seq");
		
		if ("insert".equals(request.getParameter("mode"))) {
			BoardDto dto = new BoardDto();
			dto.setWRITER(WRITER);
			dto.setPASSWORD(PASSWORD);
			dto.setTITLE(TITLE);
			dto.setCONTENT(CONTENT);
			boardDao.doInsert(dto);
		} else if ("modify".equals(request.getParameter("mode"))) {
			BoardDto dto = new BoardDto();
			dto.setSEQ(new Integer(SEQ));
			dto.setWRITER(WRITER);
			dto.setPASSWORD(PASSWORD);
			dto.setTITLE(TITLE);
			dto.setCONTENT(CONTENT);
			boardDao.doUpdate(dto);
		}
		
		mav.setView(new RedirectView("boardList.do"));
		return mav;
		
	}

}
